package com.hq.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hq.zb.dto.CustomerInfoDto;
import com.hq.zb.dto.LiaisonInfoDto;
import com.hq.zb.exception.BizException;
import com.hq.zb.exception.BizExceptionEnum;
import com.hq.zb.mapper.CustomerInfoMapper;
import com.hq.zb.model.CustomerInfo;
import com.hq.zb.model.LiaisonInfo;
import com.hq.zb.service.ICustomerInfoService;
import com.hq.zb.service.ILiaisonInfoService;
import com.hq.zb.vo.CustomerInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 客户基本信息 服务实现类
 * </p>
 *
 * @author huanghanrui
 * @since 2022-03-24
 */
@Service
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements ICustomerInfoService {

    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    @Autowired
    private ILiaisonInfoService liaisonInfoService;

    @Override
    public void saveCustomerInfo(CustomerInfoDto customerInfoDto) {
        if (StringUtils.isEmpty(customerInfoDto.getCustomerName())) {
            throw new BizException(BizExceptionEnum.DATA_NOT_NULL, "客户名称不允许为空.");
        }
        CustomerInfo customerInfo = new CustomerInfo();
        BeanUtil.copyProperties(customerInfoDto, customerInfo);
        if (customerInfo.getCustomerId() == null) {
            customerInfoMapper.insert(customerInfo);
        } else {
            customerInfoMapper.updateById(customerInfo);
        }
        //保存联系人信息
        List<LiaisonInfoDto> liaisonInfos = customerInfoDto.getLiaisonInfos();
        if (CollectionUtil.isNotEmpty(liaisonInfos)) {
            for (LiaisonInfoDto liaisonInfoDto : liaisonInfos) {
                LiaisonInfo liaisonInfo = new LiaisonInfo();
                BeanUtil.copyProperties(liaisonInfoDto, liaisonInfo);
                if (liaisonInfo.getId() == null) {
                    liaisonInfoService.insert(liaisonInfo);
                } else {
                    liaisonInfoService.updateById(liaisonInfo);
                }
            }
        }
    }

    @Override
    public Page<CustomerInfoVo> queryCustomerInfo(Page<CustomerInfoVo> page, CustomerInfoDto dto) {
        List<CustomerInfoVo> customerInfos = customerInfoMapper.queryCustomerInfo(dto);
        page.setRecords(customerInfos);
        return page;
    }
}
